package com.codebase.zookeeper.zk;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 获取子节点
 */
public class GetChildren implements Watcher {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zk = null;


    @Override
    public void process(WatchedEvent event) {
        if(event.getState() == Event.KeeperState.SyncConnected){
            if(EventType.None == event.getType() && null == event.getPath()){
                countDownLatch.countDown();
            } else if(event.getType() == Event.EventType.NodeChildrenChanged){
                try {
                    System.out.println("获取子节改变：" + zk.getChildren(event.getPath(), true));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 同步获取子列表
     * @throws Exception
     */
    @Test
    public void test1() throws Exception{
        String path = "/root";
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new GetChildren());
        countDownLatch.await();
        zk.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.create(path+"/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        List<String> childrenList = zk.getChildren(path, true);
        System.out.println(childrenList);

        zk.create(path+"/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        Thread.sleep(3000);
    }

    /**
     * 异步获取子节点列表
     * @throws Exception
     */
    @Test
    public void test2() throws Exception{
        String path = "/root";
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new GetChildren());
        countDownLatch.await();
        zk.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.create(path+"/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        zk.getChildren(path,true, new MyChlidrenCallBack(), "ctx数据");

        zk.create(path+"/c2", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        Thread.sleep(3000);
    }

    class MyChlidrenCallBack implements AsyncCallback.Children2Callback{
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
            System.out.println("响应code" + rc);
            System.out.println("param path" + path);
            System.out.println("ctx" + ctx);
            System.out.println(children);
            System.out.println("节点状态"+stat);
        }
    }


}
